package api

import (
	"server/global"
	"server/internal/app/task"
	"server/internal/middleware"
	"server/internal/model"
	"server/internal/pkg/response"
	"server/internal/services"

	"github.com/gin-gonic/gin"
)

// RoomApi 直播间
var RoomApi = new(roomApi)

type roomApi struct {
	model.Room
}

// Router 路由
func (a roomApi) Router(r *gin.RouterGroup) {
	api := r.Group("/room", middleware.LoginVerification, middleware.PermissionVerification)
	{
		api.GET("/list", a.list)
		api.GET("/edit", a.detail)
		api.GET("/kaishitongbu", a.kaishitongbu)
		api.GET("/kaishifafang", a.kaishifafang)
		api.POST("/add", a.add)
		api.POST("/edit", a.edit)
		api.POST("/del", a.del)
	}
}

// List 列表
func (a roomApi) list(c *gin.Context) {
	Db := global.GL_DB
	list, total := services.GetPagingList(Db, a, c, "title")
	response.SuccessList(c, list, total)
}

// Detail 单条
func (a roomApi) detail(c *gin.Context) {
	id := c.Query("id")
	detail := services.GetById(id, a)
	response.SuccessData(c, detail, "")
}

// Add 添加
func (a roomApi) add(c *gin.Context) {
	if err := c.ShouldBindJSON(&a); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}

	if _, err := services.Create(a); err == nil {
		response.Success(c, "", "添加成功")
	} else {
		response.Error(c, err.Error())
	}
}

// Edit 编辑
func (a roomApi) edit(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}

	if err := services.Update(a); err == nil {
		response.Success(c, "", "编辑成功")
	} else {
		response.Error(c, err.Error())
	}
}

// Del 删除
func (a roomApi) del(c *gin.Context) {
	type Param struct {
		Ids []int `json:"ids"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}

	if services.Delete(param.Ids, a) == nil {
		response.Success(c, "", "删除成功")
	} else {
		response.Error(c, "删除失败")
	}
}

// kaishitongbu 开始同步
func (a roomApi) kaishitongbu(c *gin.Context) {
	room_id := c.Query("room_id")
	if room_id == "" {
		response.Error(c, "room_id不能为空")
		return
	}
	if task.AwardBonusStatus {
		response.Error(c, "发红包程序正在执行，请稍后再试！")
		return
	}
	if task.SyncResultsStatus {
		response.Error(c, "程序正在执行")
		return
	}

	go task.SyncResults(room_id)

	response.Success(c, "", "开始同步")
}

// kaishifafang 开始发放
func (a roomApi) kaishifafang(c *gin.Context) {
	// 获取当前本地时间
	//now := time.Now()
	//currentHour := now.Hour()
	//if currentHour < 12 {
	//	response.Error(c, "12点之后才可以手动发放")
	//	return
	//}

	room_id := c.Query("room_id")
	if room_id == "" {
		response.Error(c, "room_id不能为空")
		return
	}
	if task.SyncResultsStatus {
		response.Error(c, "用户同步程序正在执行，请稍后再试！")
		return
	}
	if task.AwardBonusStatus {
		response.Error(c, "程序正在执行")
		return
	}

	go task.AwardBonus(room_id)

	response.Success(c, "", "开始发放")
}
